﻿// <copyright file="CultureScope.cs" company="Lu Studio">
// Copyright (c) Lu Studio. All rights reserved.
// </copyright>
// <author>lu qi</author>
// <createTime>2021-06-19</createTime>

namespace ElfKit.Common
{
    using System;
    using System.Globalization;
    using System.Threading;

    /// <summary>
    /// 文化范围.
    /// </summary>
    public sealed class CultureScope : IDisposable
    {
        #region 定义

        /// <summary>
        /// 原始<see cref="CultureInfo"/>示例.
        /// </summary>
        private readonly CultureInfo originalCulture;

        /// <summary>
        /// 原始UI<see cref="CultureInfo"/>示例.
        /// </summary>
        private readonly CultureInfo originalUiCulture;

        #endregion 定义

        /// <summary>
        /// 构造函数.
        /// </summary>
        /// <param name="culture">范围内的<see cref="CultureInfo"/>示例.</param>
        public CultureScope(CultureInfo culture)
        {
            this.originalCulture = Thread.CurrentThread.CurrentCulture;
            this.originalUiCulture = Thread.CurrentThread.CurrentUICulture;

            Thread.CurrentThread.CurrentCulture = culture;
            Thread.CurrentThread.CurrentUICulture = culture;
        }

        /// <summary>
        /// 构造函数.
        /// </summary>
        /// <param name="culture">文化名称.</param>
        public CultureScope(string culture)
            : this(new CultureInfo(culture))
        {
        }

        /// <summary>
        /// 获得简体中文的<see cref="CultureScope"/>.
        /// </summary>
        public static CultureScope ZhCn
        {
            get
            {
                return new CultureScope(Constant.CultureNames.ZhCn);
            }
        }

        /// <summary>
        /// 获得英语的<see cref="CultureScope"/>.
        /// </summary>
        public static CultureScope EnUs
        {
            get
            {
                return new CultureScope(Constant.CultureNames.EnUs);
            }
        }

        /// <summary>
        /// 设置当前的文化为默认的文化.
        /// </summary>
        public static void SetDefault()
        {
            CultureInfo ci = Env.GetDefaultCulture();
            Thread.CurrentThread.CurrentCulture = ci;
            Thread.CurrentThread.CurrentUICulture = ci;
        }

        /// <summary>
        /// 释放资源.
        /// </summary>
        public void Dispose()
        {
            Thread.CurrentThread.CurrentCulture = this.originalCulture;
            Thread.CurrentThread.CurrentUICulture = this.originalUiCulture;
        }
    }
}